/*
 * @(#)SolrSearch.java 2014-12-19 上午10:13:40
 * Copyright 2014 鲍建明, Inc. All rights reserved. 8637.com
 * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 
package com.myschool.solr;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.FacetField.Count;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;

*//**
 * <p>File：SolrSearch.java</p>
 * <p>Title: </p>
 * <p>Description:</p>
 * <p>Copyright: Copyright (c) 2014 2014-12-19 上午10:13:40</p>
 * <p>Company: 8637.com</p>
 * @author 鲍建明
 * @version 1.0
 *//*
public class SolrSearch
{
	
	 private static String tomcat_solr = "http://localhost:8983/solr";
	    private static HttpSolrServer solr = null;
	  //  private static GoodsDAO goodsDAO = GoodsDAO.getInstance();
	    private static List<GoodsEntity> goodList = new ArrayList<GoodsEntity>();
	 
	    // 初始化solr服务
	    public static void initiate() {
	    	
	        try {
	            solr = new HttpSolrServer(tomcat_solr);
	            solr.setConnectionTimeout(100);
	            solr.setDefaultMaxConnectionsPerHost(100);
	            solr.setMaxTotalConnections(100);
	        } catch (Exception e) {
	            System.out.println("请检查tomcat服务器或端口是否开启!");
	            e.printStackTrace();
	        }
	    }
	 
	    // 检测good是否有字段为空
	    public static Boolean CheckGood(GoodsEntity good) {
	      return true;
	    }
	 
	    // 将数据库中的时间转换为solr可接受的格式
	    public static String Convertime(String time) {
	        time = time.replace(" ", "T");
	        time = time + "00Z";
	        return time;
	    }
	 
	    // 添加list到索引，flag为false，在原有基础上添加，为false，重新添加、原有索引不会被删除
	    public static void addGoods(List<GoodsEntity> list, Boolean flag) {
	        if (flag) {
	            try {
	                solr.deleteByQuery("*:*");
	            } catch (Exception e) {
	                e.printStackTrace();
	            }
	        }
	 
	        Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
	 
	        for (int i = 0; i < list.size(); i++) {
	        	GoodsEntity good = list.get(i);
	            if (CheckGood(good)) {
	                SolrInputDocument doc = new SolrInputDocument();
	                doc.addField("goodid", good.getGoodId());
	                doc.addField("title", good.getTitle());
	                doc.addField("siteid", good.getSiteId());
	                doc.addField("buynum", good.getBuyNum());
	                doc.addField("starttime", Convertime(good.getStartTime()
	                        .toString()));
	                doc.addField("discount", good.getDisCount());
	                doc.addField("curprice", good.getCurPrice());
	                docs.add(doc);
	            }
	        }
	 
	        try {
	            solr.add(docs);
	            solr.optimize();
	            solr.commit();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
	 
	    // 转换good到beans
	    public static GoodsEntity ConvertGoodstoBeans(GoodsEntity good) {
	        if (!CheckGood(good)) {
	            return null;
	        }
	        GoodsEntity beans = new GoodsEntity(good.getGoodId(),
	                good.getTitle(), good.getSiteId().toString(), good.getBuyNum(),
	                good.getStartTime(), good.getDisCount(), good.getCurPrice());
	        return beans;
	    }
	 
	    // 添加beans到索引
	    public static void addGoodsBeans(List<GoodsEntity> beansList) {
	        try {
	            solr.addBeans(beansList);
	        } catch (Exception e) {
	            e.printStackTrace();
	            try
				{
					solr.rollback();
				}
				catch (SolrServerException e1)
				{
					e1.printStackTrace();
				}
				catch (IOException e1)
				{
					e1.printStackTrace();
				}
	        } finally {
	            try {
	                solr.optimize();
	                solr.commit();
	            } catch (Exception e) {
	                e.printStackTrace();
	            }
	        }
	    }
	 
	    // 删除所有索引
	    public static void DeleteAllIndex() {
	        try {
	            solr.deleteByQuery("*:*");
	            solr.commit();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
	 
	    // 根据ID删除索引
	    public static void DeleteIndex(List<String> ids) {
	        try {
	            solr.deleteById(ids);
	            solr.commit();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
	 
	    // 进行搜索，field、key为查询（值或范围均可），start为起始查询位置，row为返回结果个数，sortfield为排序字段，flag中true升序、false降序，hightlight选择是否高亮返回，高亮字段为title
	    public static QueryResponse Search(String[] field, String[] key, int start,
	            int count, String[] sortfield, Boolean[] flag, Boolean hightlight) {
	        if (null == field || null == key || field.length != key.length) {
	            return null;
	        }
	        if (null == sortfield || null == flag
	                || sortfield.length != flag.length) {
	            return null;
	        }
	 
	        SolrQuery query = null;
	        try {
	            if (field[0].equals("title")) {
	                // query = new SolrQuery("*" + key + "*");
	                query = new SolrQuery(field[0] + ":" + key[0]);
	            } else {
	                query = new SolrQuery(field[0] + ":" + key[0]);
	            }
	            for (int i = 0; i < field.length; i++) {
	                if (field[i].equals("title")) {
	                    // query = new SolrQuery("*" + key + "*");
	                    query.addFilterQuery(field[i] + ":" + key[i]);
	                } else {
	                    query.addFilterQuery(field[i] + ":" + key[i]);
	                }
	            }
	            query.setStart(start);
	            query.setRows(count);
	            for (int i = 0; i < sortfield.length; i++) {
	                if (flag[i]) {
	                    query.addSortField(sortfield[i], SolrQuery.ORDER.asc);
	                } else {
	                    query.addSortField(sortfield[i], SolrQuery.ORDER.desc);
	                }
	            }
	            if (null != hightlight) {
	                query.setHighlight(true); // 开启高亮组件
	                query.addHighlightField("title");// 高亮字段
	                query.setHighlightSimplePre("<font color=\"red\">");// 标记
	                query.setHighlightSimplePost("</font>");
	                query.setHighlightSnippets(1);
	                query.setHighlightFragsize(1000);
	            }
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        System.out.println(query.toString());
	 
	        QueryResponse rsp = null;
	        try {
	            rsp = solr.query(query);
	        } catch (Exception e) {
	            e.printStackTrace();
	            return null;
	        }
	        return rsp;
	    }
	 
	    // 自动补全
	    public static String[] autoComplete(String prefix, int min) {
	        String words[] = null;
	        StringBuffer sb = new StringBuffer("");
	        SolrQuery query = new SolrQuery("*.*");
	        QueryResponse rsp = new QueryResponse();
	        try {
	            query.setFacet(true);
	            query.setQuery("*:*");
	            query.setFacetPrefix(prefix);
	            query.addFacetField("title");
	            rsp = solr.query(query);
	        } catch (Exception e) {
	            // TODO: handle exception
	            e.printStackTrace();
	            return null;
	        }
	 
	        if (null != rsp) {
	            FacetField ff = rsp.getFacetField("title");
	            List<Count> countList = ff.getValues();
	            if (null == countList) {
	                return null;
	            }
	            for (int i = 0; i < countList.size(); i++) {
	                String tmp[] = countList.get(i).toString().split(" ");
	                if (tmp[0].length() < 2) {
	                    continue;
	                }
	                sb.append(tmp[0] + " ");
	                min--;
	                if (min == 0) {
	                    break;
	                }
	            }
	            words = sb.toString().split(" ");
	        } else {
	            return null;
	        }
	        return words;
	    }
	 
	    public static void main(String[] args) {
	        initiate();
	 
	        // 建立索引
//	       goodList = goodsDAO.findAll();
//	       System.out.println("所有商品载入完成！");
//	       DeleteAllIndex();
//	       System.out.println("原有索引已清除！");
//	       System.out.println("添加索引开始！");
//	       long starttime = System.currentTimeMillis();
//	       addGoods(goodList, true);
//	       long endtime = System.currentTimeMillis();
//	       System.out.println("共耗时" + (endtime - starttime) + "ms！");
//	       System.out.println("添加索引完成！");
	 
	        // 进行查询
	        SolrDocumentList solrList = null;
	        QueryResponse rsp = null;
	 
	        // rsp = Search("title", "*变形金* 蓝精灵", 0, 10, "buynum", false, true);
//	      String field[] = { "title", "buynum", "discount", "starttime" };
//	      String key[] = { "变形金刚 哈利波特", "[90 TO 100]", "[2.0 TO 3.0]",
//	              "[2011-07-18T00:00:00.000Z TO 2011-07-19T00:00:00.000Z]" };
	        String field[] = {"title"};
	        String key[] = {"牛奶"};
	        String sortfield[] = { "buynum" };
	        Boolean flag[] = { false };
	        long starttime = System.currentTimeMillis();
	        rsp = Search(field, key, 0, 10, sortfield, flag, true);
	        long endtime = System.currentTimeMillis();
	        System.out.println("共耗时" + (endtime - starttime) + "ms！");
	 
	        if (null != rsp) {
	            solrList = rsp.getResults();
	            for (int i = 0; i < solrList.size(); i++) {
	                System.out.println(solrList.get(i).toString());
	            }
	            // 高亮显示部分
	            System.out.println("搜索结果共" + solrList.size() + "条！");
	            System.out.println("");
	            Map<String, Map<String, List<String>>> hightlight = rsp
	                    .getHighlighting();
	            for (int i = 0; i < tmpLists.size(); i++) {
	                String hlString = hightlight.get(tmpLists.get(i).getGoodId())
	                        .get("title").toString();
	                if (null != hlString) {
//	                  System.out.println(hlString);
	                }
	            }
	        }
	 
	        // 自动补全
	        // String words[] = autoComplete("哈利", 10);
	        // if (null != words) {
	        // System.out.println(words.length);
	        // for (int i = 0; i < words.length; i++) {
	        // System.out.println(words[i]);
	        // }
	        // }
	    }
}
*/